package net.zoneland.knowledge.service.impl;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.google.common.collect.Lists;
import net.zoneland.knowledge.controller.bean.UomUserOrgQueryVo;
import net.zoneland.knowledge.dao.RoleMapper;
import net.zoneland.knowledge.dao.UserRoleRelMapper;
import net.zoneland.knowledge.enums.PurviewEnum;
import net.zoneland.knowledge.model.LoginUserPojo;
import net.zoneland.knowledge.model.PartyOrg;
import net.zoneland.knowledge.model.PartyUser;
import net.zoneland.knowledge.model.Role;
import net.zoneland.knowledge.model.UserRoleRel;
import net.zoneland.knowledge.model.UserRoleRelExample;
import net.zoneland.knowledge.service.PartyService;
import net.zoneland.knowledge.service.PermissionService;
import net.zoneland.knowledge.service.RoleService;
import net.zoneland.knowledge.service.UserService;
import net.zoneland.uniflow.client.UserInfo;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * .
 *
 * @author: bcc
 * 2021/6/4
 */
@Service
public class RoleServiceImpl implements RoleService {

    /**
     * 日志.
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(RoleServiceImpl.class);

    @Autowired
    private UserService userService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleRelMapper userRoleRelMapper;

    /**
     * 党员/党组织业务接口.
     */
    @Autowired
    private PartyService partyService;

    /**
     * 职务权限服务.
     */
    @Autowired
    private PermissionService permissionService;

    @Override
    public List<Role> getByUserId(final String userId) {
        return roleMapper.getByUserId(userId);
    }

    @Override
    public List<UserRoleRel> getByRoleIds(final List<String> roleIds) {
        final UserRoleRelExample example = new UserRoleRelExample();
        example.createCriteria().andRoleidIn(roleIds);
        return userRoleRelMapper.selectByExample(example);
    }

    /**
     * 从后台角色获取角色对应用户
     * @return
     */
    @Override
    public List<UserInfo> getUserInfoFromRole(String roleName) {
        List<UserRoleRel> roleUser = getByRoleIds(Lists.newArrayList(roleName));
        return roleUser.stream().map(item-> {
            try {
                LoginUserPojo userByUid = userService.getUserByUid(item.getUserid());
                if (null != userByUid) {
                    return new UserInfo(userByUid.getUserID(), userByUid.getUserName());
                }

            } catch (Exception e) {
                LOGGER.error("getUserInfoFromRole error, userId:{}",item.getUserid(), e);
            }
            return null;
        }).filter(item -> null != item).collect(Collectors.toList());
    }

    /**
     * 获取党委书记.
     * @param orgUuid 党组织id.
     * @return 党委书记
     */
    @Override
    public UserInfo getDwsjByOrgUuid(final String orgUuid) {
        if (StringUtils.isBlank(orgUuid)) {
            return null;
        }
        final PartyOrg partyOrg = partyService.getOrgByUuid(orgUuid);
        if (null == partyOrg) {
            return null;
        }

        final UomUserOrgQueryVo param = new UomUserOrgQueryVo();
        param.setMobile(partyOrg.getSjMobile());
        param.setDoNotfillMore(true);
        param.setIgnoreHiddenInfo(true);
        final List<PartyUser> partyUsers = partyService.searchByCondition(param);
        if (CollectionUtils.isNotEmpty(partyUsers)) {
            final PartyUser partyUser = partyUsers.get(0);
            UserInfo userInfo = new UserInfo();
            userInfo.setUserId(partyUser.getOaId());
            userInfo.setUserName(partyUser.getDisplayName());
            return userInfo;
        }
        return null;
    }

    /**
     * 根据用户获取角色信息列表.
     * 根据用户id获取配置的角色，根据用户职务获取职务权限信息，合并去重返回.
     * @param userPojo 用户信息对象.
     * @return 返回角色信息列表.
     */
    @Override
    public List<Role> getRoleListByUser(final LoginUserPojo userPojo) {
        //从用户信息里获取职务编码列表.
        final List<String> naviCodeList = userPojo.getPurviewEnums().stream().filter(Objects::nonNull)
                .map(PurviewEnum::getNaviCode)
                .collect(Collectors.toList());
        //根据职务编码查询权限信息.
        final List<String> dutyPermissionsList = permissionService.queryPermissionsByNaviCodeList(naviCodeList);
        //根据用户id查询该角色配置的权限信息.
        final List<String> roleList = roleMapper.getRoleIdByUserId(userPojo.getUserID());
        //合并配置的角色信息和根据职务查询出来的权限信息，并根据角色id去重返回
        return Stream.of(dutyPermissionsList, roleList)
            .flatMap(Collection::stream)
            .distinct()
            .map(Role::new)
            .collect(Collectors.toList());
    }
}
